let mysql = require("mysql")
//创建数据库连接池
let pool = mysql.createPool({
  connectionLimit: 20,
  host: "localhost",
  port: 3306,
  user: "root",
  password: "",
  database: "myshop"
});

//定义一个数据库的查询方法
/* 
sql => 查询的语句
value => 查询语句中的值
callback => 查询成功后的回调函数
*/
function query(sql, values, callback) {
  // console.log("查询语句", sql, "-------查询的值", values)
  pool.getConnection(function (err, connection) {
    if (err) throw err
    connection.query(sql, values, function (err, results, fields) {
      callback(err, results, fields)
      //释放链接
      connection.release()
    })
  })
}

function queryPromise(sql, values) {
  console.log("查询语句", sql, "-------查询的值", values)
  return new Promise(function (resolve, reject) {
    pool.getConnection(function (err, connection) {
      if (err) throw err
      connection.query(sql, values, function (err, results, fields) {
        resolve({err, results, fields})
        //释放链接
        connection.release()
      })
    })
  })
}

//定义一个函数， 根据cat_id 返回菜单的数据
function query_cat(cat_id) {
  let sql = "select * from menu where cat_id = ?"
  return new Promise(function (resolve, reject) {
    query(sql, [cat_id], function (err, results, fields) {
      resolve(results)
    })
  })
}
exports.query = query
exports.query_cat = query_cat
exports.queryPromise = queryPromise